package com.zztl.infiniteBand.util

import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.PixelFormat
import android.graphics.drawable.Drawable
import android.net.Uri
import android.os.Environment
import android.provider.MediaStore

import java.io.File
import java.io.FileNotFoundException
import java.io.FileOutputStream
import java.io.IOException

/**
 * @author ARZE
 * @version 创建时间：2016年4月23日 下午5:55:00
 * @说明 图片操作类 用于相机拍照后的数据处理
 */
object ImageUtil {

    fun saveBitmap2Gallery(context: Context, bitmap: Bitmap, dirName: String, listerer: SavaImageListerer?) {

        val fileDir = File(Environment.getExternalStorageDirectory(), dirName)
        if (!fileDir.exists()) {
            fileDir.mkdirs()
        }
        val fileName = System.currentTimeMillis().toString() + ".jpeg"
        val file = File(fileDir, fileName)
        try {
            val outputStream = FileOutputStream(file)
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream)
            outputStream.flush()
            outputStream.close()

        } catch (e: FileNotFoundException) {
            listerer?.saveFail()
            e.printStackTrace()
            return
        } catch (e: IOException) {
            listerer?.saveFail()
            e.printStackTrace()
            return
        }

        //把图片插入到系统图库
        try {
            MediaStore.Images.Media.insertImage(context.contentResolver, file.absolutePath, fileName, null)
            //通知图库更新
            context.sendBroadcast(Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + file.absolutePath)))
            listerer?.saveSuccess()
        } catch (e: FileNotFoundException) {
            listerer?.saveFail()
            e.printStackTrace()
        }


    }

    fun drawableTobitmap(drawable: Drawable): Bitmap {
        val width = drawable.intrinsicWidth
        val height = drawable.intrinsicHeight
        val config = if (drawable.opacity != PixelFormat.OPAQUE) Bitmap.Config.ARGB_8888 else Bitmap.Config.RGB_565
        val bitmap = Bitmap.createBitmap(width, height, config)
        val canvas = Canvas(bitmap)
        drawable.setBounds(0, 0, width, height)
        drawable.draw(canvas)
        return bitmap
    }

    interface SavaImageListerer {
        fun saveSuccess()

        fun saveFail()
    }


}
